<?php
class SearchsController extends AppController{

     var $name='Searchs';
     var $uses = array("SearchCompany","Techstack","Talstack","CompTechnology","CompTalent","CompFinacerelease",
                        "Codetype","Constant","Company","CompPage","CompTrackinfo","CompCarrierlease","CompDormitorylease",
                        "CompDemand","CompFinacerelease","CompJobapply","CompanyPatent","CompEconomic","Group");     
     var $helpers=array('Pagination','Html','Javascript','Form','Str','Action','Accp');
     var $components = array ('Pagination','Cookie');
     var $layout='hindex';
    
    function index()
    {
        $this->loadModel("Codetype");
        $this->loadModel("Constant");
        $grouplist=$this->Group->getGroupList();
        $techtype=$this->Codetype->getSubType($this->Constant->TalstackType,"-",1);
        $dtypes=$this->Codetype->getCValues($this->Constant->TechnologyReport,1);
        $talstacktype=$this->Codetype->getSubType($this->Constant->TalstackType);	
        $dstatus=$this->Codetype->getCValues($this->Constant->Declarate_Status,1);
//		$option=$this->Techstack->getValue(1);
        $industrys=$this->Codetype->getCValues($this->Constant->Industry,"all");
        $selecttalstacktype=null;
        $selectdstatus=null;
        $pagesize=10;
        $paging['show']=$pagesize;
        $paging['url'] = '/searchs/index/';
        $urlcount=0;
        
        $where="";
        $year="";
        if(!empty($_GET['year'])){
            $year=$_GET['year'];;
        }
        $type="";
        if(!empty($_GET['type'])){
            $type=$_GET['type'];
        }
        $state="";
        if(isset($_GET['states'])){
            $state=$_GET['states'];
        }
        $auditstatus = "";
        if(isset($_GET['auditstatus'])){
            $auditstatus=$_GET['auditstatus'];
        }
        if(!empty($_GET['dstatus'])){
            $selectdstatus=$_GET['dstatus'];
        }
        $gov="";
        if(!empty($_GET['gov'])){
            $selecttalstacktype=$_GET['gov'];
        }
        $group='';
        if(!empty($_GET['group'])){
        	$group=$_GET['group'];
        }
        $group_mod_id=$_GET['group'];
        
        $isflag=false;
        $sql="";
        if(!empty($_GET['year'])){
            $isflag=true;
            $sql.="(year(CompTechnology.apply_time)='$year' or 
            year(CompTechnology.accept_time)='$year' or 
            year(CompTechnology.authorize_time)='$year') and ";
        }
        if(!empty($_GET['gov'])){
            $sql.="CompTechnology.department='".$selecttalstacktype."' and ";
            $isflag=true;
        }
        if(!empty($_GET['type']) ){
            $sql.="CompTechnology.type_id='$type' and ";
            $isflag=true;
        }
        if(!empty($_GET['dstatus'])){
            $sql.="CompTechnology.declarate_status='".$selectdstatus."' and ";
            $isflag=true;
        }
        if(isset($_GET['auditstatus'])){
            $isflag=true;
            $sql.="CompTechnology.status = '".$auditstatus."' and ";
        }
        if(isset($_GET['states']) ){
            $isflag=true;
            $sql.="CompTechnology.state='$state' and ";
        }
        //增加模块检索
        $cuser=$this->Session->read('User');
        if(!$cuser['isadmin']&&!$cuser['isvisitor']){
			$isflag=true;
        	$sql.="Company.groupid='".$cuser["groupid"]."' and ";		
        }else{
        	if(!empty($_GET['group'])){
        		$isflag=true;
        		$sql.="Company.groupid='".$_GET['group']."' and ";
        	}
        }
    	 $group_mod_id=$_GET['group'];
        $flag=false;
        if(!empty($_GET['year']) && !empty($_GET['type']) && !empty($_GET['gov']) && !empty($_GET['dstatus']) && isset($_GET['states'])&& isset($_GET['$auditstatus'])){
            $flag=true;
        }
        if(!empty($_GET['year']) && !empty($_GET['gov']) && isset($_GET['states'])|| $flag){
            $isflag=true;
            $sql.="CompTechnology.state='$state' and ";
            if($flag){
                $sql.="CompTechnology.type_id='$type' and ";
            }
            switch ($state){
                case "0":
                    $sql.="year(CompTechnology.apply_time)='$year' and";
                    break;
                case "1":
                    $sql.="year(CompTechnology.accept_time)='$year' and";
                    break;
                case "2":
                    $sql.="year(CompTechnology.authorize_time)='$year' and";
                    break;
            }
        }	
        $keyword="";
        if(!empty($_GET['keyword'])){
            $isflag=true;
            $keyword=$_GET['keyword'];
            $sql.="CompTechnology.tname like '%".urldecode($keyword)."%' and ";
        }
        if($isflag){
            $this->CompTechnology->unbindModel(array ('hasMany' => array ('Attachment'),'belongsTo' => array ('type_id')));
            $objcids=$this->CompTechnology->findAll("$sql CompTechnology.is_deleted='0'","CompTechnology.cid");
            $cidlist="";
            foreach ($objcids as $cid){
                $cidlist.="'".$cid["CompTechnology"]["cid"]."',";
            }
            if($cidlist){
                $where.="SearchCompany.id in (".rtrim($cidlist,",").") and ";
            }else{
                $where.="SearchCompany.id in (1) and ";
            }
        }
        $industry="";
        if(!empty($_GET['industry'])){
            $industry=$_GET['industry'];
            $this->loadModel("ProCvalue");
            $objpidlist=$this->ProCvalue->findAllByCvid($industry);
            $pidlist="";
            if($objpidlist){
                foreach ($objpidlist as $pid){
                    $pidlist.="'".$pid["ProCvalue"]["pid"]."',";
                }
            }
            $wheres=rtrim($pidlist,",");	
            if(empty($wheres)){
                $wheres=1;
            }
            $where.="SearchCompany.id in (".$wheres.") and ";
        }
        $enterprise="";
        if(!empty($_GET['enterprise'])){
            $enterprise=$_GET['enterprise'];
            $where.="SearchCompany.company_name like '%".urldecode($enterprise)."%' and ";
        }
        $where.="SearchCompany.is_deleted='0'";
        $urlcount=$this->SearchCompany->findCount($where);
        if(!empty($_GET['year']) || !empty($_GET['type']) || isset($_GET['states']) || !empty($_GET['keyword'])||!empty($_GET['gov'])||!empty($_GET['type'])||isset($_GET['auditstatus'])||!empty($_GET['dstatus'])){
            $this->Session->setFlash('共检索出'.$urlcount.'条记录');
        }
        $paging['total'] =$urlcount;
        $showpage=0;
        $companys=array();
        if ($paging['total'] > 0) {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
            $this->SearchCompany->bindModel(
                array('hasMany' => array(
                'CompTechnology' => array (
                'conditions' => array(" $sql is_deleted='0'"),
                'fields'=>"`CompTechnology`.`id`,`CompTechnology`.`state`,`CompTechnology`.`status`,`CompTechnology`.`apply_time`, `CompTechnology`.`accept_time`,
                `CompTechnology`.`authorize_time`, `CompTechnology`.`tname`,`CompTechnology`.`department`,`CompTechnology`.`type_id`,`CompTechnology`.`declarate_status`",
                'order'=>'CompTechnology.state asc',
                'className' => 'CompTechnology',
                'foreignKey' => 'cid',)
                ))
            );
            $companys=$this->SearchCompany->findAll($where,"SearchCompany.id,SearchCompany.pid,SearchCompany.company_name,SearchCompany.groupid","SearchCompany.modified desc",$limit,$page);
            if($urlcount>$pagesize)
            {
                $showpage=1;
            }
        }
        $this->set(compact('group_mod_id','companys','showpage','year','type','state','option','industrys','industry','keyword','dstatus','talstacktype','selecttalstacktype','selectdstatus','dtypes','techtype','auditstatus','enterprise','grouplist'));
    }
    
    function showtalent($id,$cid,$cname){
        $this->Session->write('companyid', $cid);
        $this->Session->write('companyname', $cname);
        $talstack=$this->CompTalent->findById($id);
        $filetypes=$this->Codetype->getCValues($this->Constant->Personfile,1);
        $statues=$this->Codetype->getCValues($this->Constant->Declarate_Status);
        $this->loadModel("Talstack");
        $this->Talstack->unbindModel(array ('belongsTo' => array ('Codevalue')));
        $declaretype=$this->Talstack->getTname();
        $this->set(compact('declaretype','filetypes'));
        $attachments=array();
        $objCompTalent=$this->CompTalent->findById($id);	
            $attachments=$objCompTalent["Attachment"];
            $this->data =$objCompTalent;
            $declare_time=$objCompTalent["CompTalent"]["declare_time"];
            if($declare_time){
                $this->data["CompTalent"]["declare_time"]=date("Y-m-d",strtotime($declare_time));
            }
        
//		$talstacktype=$this->Codetype->getSubType($this->Constant->TalstackType);		
        $talstacktype=$this->Codetype->getSubType($this->Constant->TalstackType,"-",1);		
        $this->set(compact('taltype','talstacktype','talstack','attachments','id','statues','talstacktype'));
        
    }
    //科技项目显示
    function showtechnology($id=null,$cid,$cname){
        $this->Session->write('companyid', $cid);
        $this->Session->write('companyname', $cname);
        $this->CompTechnology->id = $id;
        $technology = $this->CompTechnology->read();
        $techname = $technology["CompTechnology"]["tname"];
        $company = $this->Company->findById($technology['CompTechnology']['cid']);
        $attachments ='';
        $attachments=$technology["Attachment"];
        $types=$this->Codetype->getCValues($this->Constant->TechnologyReport);
        $statues=$this->Codetype->getCValues($this->Constant->Declarate_Status);
        $charge=$this->Codetype->getCValues($this->Constant->Depart_Charge);
        $talstacktype=$this->Codetype->getSubType($this->Constant->TalstackType,"-",1);	
        $this->set(compact('technology','attachments','company','types','charge','talstacktype','statues',"techname",'id'));
    }
    //显示企业信息
    function showinfo($id=null)
    {
        $industrys=$this->Codetype->getCValues($this->Constant->Industry,1);//所属产业
        $ctypes=$this->Codetype->getCValues($this->Constant->Companytype,1);//企业类型
        $this->set(compact('industrys','ctypes'));
        $pros_cvalues=array();
        $companytypes=array();
        $attachments=array();
        $logo=array();
        if($id){
            $objcompany=$this->Company->findById($id);	
            $this->Session->write('companyid', $id);
            $this->Session->write('companyname', $objcompany["Company"]["company_name"]);
            $this->data=$objcompany;
            $pros_cvalues=$objcompany["pros_cvalue"];//在Company的Model中定义了三个表和Compay表的关系
            $companytypes=$objcompany["CompType"];
            $attachments=$objcompany["Attachment"];
            $logo=$objcompany["Logo"];
            $reg_time=$this->data["Company"]["reg_time"];
            if($reg_time){
                $this->data["Company"]["reg_time"]=date("Y-m-d",strtotime($reg_time));
            }
            $resident_time=$this->data["Company"]["resident_time"];
            if($resident_time){
                $this->data["Company"]["resident_time"]=date("Y-m-d",strtotime($resident_time));
            }
        }
        $this->set(compact('pros_cvalues','companytypes','attachments','logo','id'));
    }
    //获取美元汇率
    function getrate(){
        return $this->Codetype->getrate();
    }
    var $strdesc="";
    function formatfilterstr($columnstr,$min,$max){
        App::import('Helper', 'Str');
        $str = new StrHelper();
        $this->strdesc.="，".$columnstr.$str->strarea($min,$max);	
    }
    function formatfilter($columnstr,$column,$min,$max,$index=null){
        $where="";
        $dan="";
        if($index=="1"){
            $dan="'";
        }
        if($min){
            $where.=$column.">=".$dan.$min.$dan." and ";
        }
        if($max){
            $where.=$column."<=".$dan.$max.$dan." and ";
        }
        if($columnstr && ($min || $max)){
            $this->formatfilterstr($columnstr,$min,$max);
        }
        return $where;
    }
    //企业基本参数
    
    function gettechfilter($techs){
        $where="";
        if($techs){
            $tid=$techs["id"];
            $tname=$techs["name"];
            $desc=$techs["desc"];
            $reg_mintime=$techs["reg_mintime"];
            $reg_maxtime=$techs["reg_maxtime"];
            $columnstr="注册时间：";
            $column="SearchCompany.reg_time";
            $where.=$this->formatfilter($columnstr,$column,$reg_mintime,$reg_maxtime,"1");
            $reg_mincaptital=$techs["reg_mincaptital"];
            $reg_maxcaptital=$techs["reg_maxcaptital"];
            $rate=0;
            if($reg_mincaptital || $reg_maxcaptital){	
                $rate=$this->getrate();
                $columnstr="注册资金(万)：";
                $column="(case SearchCompany.cap_type when '1' then SearchCompany.capital*".$rate." else SearchCompany.capital end)";
                $where.=$this->formatfilter($columnstr,$column,$reg_mincaptital,$reg_maxcaptital);
            }
                
            $reg_minsize=$techs["reg_minsize"];
            $reg_maxsize=$techs["reg_maxsize"];
            $columnstr="孵化面积(平方米)：";
            $column="SearchCompany.size";
            $where.=$this->formatfilter($columnstr,$column,$reg_minsize,$reg_maxsize);
            $this->set(compact('tname','desc','tid'));
        }
        return $where;
    }
    //人员信息
    function gettechpersonfilter($techpersons){
        $where="";
        if($techpersons){
            $total=$techpersons["total"];
            $column="(select count(id) from comp_people
                     where SearchCompany.id=comp_people.cid and is_deleted='0')";
            $columnstr="人员总数(个)：";
            $where.=$this->formatfilter($columnstr,$column,$total,"");
            $education=$techpersons["education"];
            $ed_above=$techpersons["ed_above"];
            $ed_proportion=$techpersons["ed_proportion"];
            if($education && ($ed_above || $ed_proportion)){
                App::import('Helper', 'Str');
                $str = new StrHelper();
                $this->strdesc.="，所占学历";
                $educations=$this->Constant->Education;
                $ed=$str->getkeystr($education,$educations)."以上≥";
                if($education==1){
                    $education=3;
                }
                if($ed_above){
                    $column="(select count(id) from comp_people
                        where SearchCompany.id=comp_people.cid and education<=".$education." and is_deleted='0')";
                    $where.=$this->formatfilter("",$column,$ed_above,"");
                    $this->strdesc.="人数:".$ed.$ed_above;
                }
                if($ed_proportion){
                    $column1="(select count(id) from comp_people
                        where SearchCompany.id=comp_people.cid and education<=".$education." and is_deleted='0')";
                    $column2="/(select count(id) from comp_people
                         where SearchCompany.id=comp_people.cid and is_deleted='0')";
                    $where.=$this->formatfilter("",$column1.$column2,$ed_proportion/100,"");
                    $this->strdesc.="比例:".$ed.$ed_proportion."%";
                }
            }
        }
        return $where;
    }
    //经济指标
    function gettecheconomicfilter($techeconomics){
        $where="";
        if($techeconomics){
            $min_company_year=$techeconomics["min_company_year"];	
            $max_company_year=$techeconomics["max_company_year"];
            if($min_company_year || $max_company_year){
                $columnstr="，经济指标(年)：";
                App::import('Helper', 'Str');
                $str = new StrHelper();
                $this->strdesc.=$columnstr.$str->strarea($min_company_year,$max_company_year);	
                $price="";
                $min_general_income=$techeconomics["min_general_income"];
                $max_general_income=$techeconomics["max_general_income"];	
                $columnstr="总收入(元)：";
                $column="sum(general_income)";
                $price.=$this->formatfilter($columnstr,$column,$min_general_income,$max_general_income);
                $min_prospect=$techeconomics["min_prospect"];
                $max_prospect=$techeconomics["max_prospect"];
                $columnstr="净利润(元)：";	
                $column="sum(prospect)";
                $price.=$this->formatfilter($columnstr,$column,$min_prospect,$max_prospect);
                $min_gross_output=$techeconomics["min_gross_output"];
                $max_gross_output=$techeconomics["max_gross_output"];	
                $columnstr="工业总产值(元)：";
                $column="sum(gross_output)";
                $price.=$this->formatfilter($columnstr,$column,$min_gross_output,$max_gross_output);
                $min_net_profit=$techeconomics["min_net_profit"];
                $max_net_profit=$techeconomics["max_net_profit"];	
                $columnstr="产品销售额(元)：";
                $column="sum(net_profit)";
                $price.=$this->formatfilter($columnstr,$column,$min_net_profit,$max_net_profit);
                $min_pro_taxe=$techeconomics["min_pro_taxe"];
                $max_pro_taxe=$techeconomics["max_pro_taxe"];	
                $columnstr="利税(元)：";
                $column="sum(pro_taxe)";
                $price.=$this->formatfilter($columnstr,$column,$min_pro_taxe,$max_pro_taxe);
                $min_over_taxes=$techeconomics["min_over_taxes"];
                $max_over_taxes=$techeconomics["max_over_taxes"];	
                $columnstr="上缴税金(元)：";
                $column="sum(over_taxes)";
                $price.=$this->formatfilter($columnstr,$column,$min_over_taxes,$max_over_taxes);
                $min_qcll=$techeconomics["min_qcll"];
                $max_qcll=$techeconomics["max_qcll"];	
                $columnstr="出口创汇(元)：";
                $column="sum(qcll)";
                $price.=$this->formatfilter($columnstr,$column,$min_qcll,$max_qcll);
                $min_taxindex=$techeconomics["min_taxindex"];
                $max_taxindex=$techeconomics["max_taxindex"];	
                $columnstr="减免税指标(元)：";
                $column="sum(taxindex)";
                $price.=$this->formatfilter($columnstr,$column,$min_taxindex,$max_taxindex);
                $min_tax=$techeconomics["min_tax"];
                $max_tax=$techeconomics["max_tax"];	
                $columnstr="高企减免税(元)：";
                $column="sum(tax)";
                $price.=$this->formatfilter($columnstr,$column,$min_tax,$max_tax);
                $min_devtax=$techeconomics["min_devtax"];
                $max_devtax=$techeconomics["max_devtax"];	
                $columnstr="研发费减免税(元)：";
                $column="sum(devtax)";
                $price.=$this->formatfilter($columnstr,$column,$min_devtax,$max_devtax);
                if($price){
                    $price=rtrim($price," and ");	
                }
                if($min_company_year){
                    $column="(select count(id) from comp_economics
                                 where SearchCompany.id=comp_economics.cid and company_year>=".$min_company_year." and is_deleted='0'
                                 group by company_year having $price)";
                }
                if($max_company_year){
                    $column="(select count(id) from comp_economics
                                 where SearchCompany.id=comp_economics.cid and company_year<=".$max_company_year." and is_deleted='0'
                                 group by company_year having $price)";
                }
                if($min_company_year && $max_company_year){
                    $column="(select count(id) from comp_economics
                                 where SearchCompany.id=comp_economics.cid and company_year>=".$min_company_year." and company_year<='".$max_company_year."' and is_deleted='0'
                                 group by company_year having $price)";
                }
                $where.=$this->formatfilter("",$column,1,"");
            }
        }
        return $where;
    }
    //知识产权
    function gettechpatentfilter($techpatents){
        $where="";
        if($techpatents){
            $type_id=$techpatents["type_id"];
            $type_above=$techpatents["type_above"];
            if($type_id && $type_above){
                $column="(select count(id) from company_patents
                         where SearchCompany.id=company_patents.cid and type_id='".$type_id."' and state='2' and is_deleted='0')";
                $where.=$this->formatfilter("",$column,$type_above,"");
                App::import('Helper', 'Str');
                $str = new StrHelper();
                $this->strdesc.="，知识产权指标(个)：";
                $patenttype = $this->Codetype->getCValues($this->Constant->PatentType,1);
                $this->strdesc.=$str->getkeystr($type_id,$patenttype)."≥".$type_above;
            }
        }
        return $where;
    }
    //研发费用
    function gettechdevelopmentcostfilter($techdevelopmentcosts){
        $where="";
        if($techdevelopmentcosts){
            $min_c_time=$techdevelopmentcosts["min_c_time"];	
            $max_c_time=$techdevelopmentcosts["max_c_time"];
            if($min_c_time || $max_c_time){
                $columnstr="，研发费用投入(年)：";
                App::import('Helper', 'Str');
                $str = new StrHelper();
                $this->strdesc.=$columnstr.$str->strarea($min_c_time,$max_c_time);	
                $price="";
                $min_cost=$techdevelopmentcosts["min_cost"];
                $max_cost=$techdevelopmentcosts["max_cost"];
                $columnstr="投入总额(元)：";
                $column="sum(cost)";
                $price.=$this->formatfilter($columnstr,$column,$min_cost,$max_cost);
                $min_research_exp=$techdevelopmentcosts["min_research_exp"];
                $max_research_exp=$techdevelopmentcosts["max_research_exp"];
                $columnstr="研究与实验(元)：";	
                $column="sum(research_exp)";
                $price.=$this->formatfilter($columnstr,$column,$min_research_exp,$max_research_exp);
                $min_new_product=$techdevelopmentcosts["min_new_product"];
                $max_new_product=$techdevelopmentcosts["max_new_product"];	
                $columnstr="新产品费用(元)：";
                $column="sum(new_product)";
                $price.=$this->formatfilter($columnstr,$column,$min_new_product,$max_new_product);
                $min_govern_funding=$techdevelopmentcosts["min_govern_funding"];
                $max_govern_funding=$techdevelopmentcosts["max_govern_funding"];
                $columnstr="政府拨款(元)：";	
                $column="sum(govern_funding)";
                $price.=$this->formatfilter($columnstr,$column,$min_govern_funding,$max_govern_funding);
                $min_raised_enterprise=$techdevelopmentcosts["min_raised_enterprise"];
                $max_raised_enterprise=$techdevelopmentcosts["max_raised_enterprise"];	
                $columnstr="企业自筹费用(元)：";
                $column="sum(raised_enterprise)";
                $price.=$this->formatfilter($columnstr,$column,$min_raised_enterprise,$max_raised_enterprise);
                $price=rtrim($price," and ");	
                if($min_c_time){
                    $column="(select count(id) from development_costs
                                 where SearchCompany.id=development_costs.cid and c_time>=".$min_c_time." and is_deleted='0'
                                 group by year(c_time) having $price)";
                }
                if($max_c_time){
                    $column="(select count(id) from development_costs
                                 where SearchCompany.id=development_costs.cid and c_time<=".$max_c_time." and is_deleted='0'
                                 group by year(c_time) having $price)";
                }
                if($min_c_time && $max_c_time){
                    $column="(select count(id) from development_costs
                                 where SearchCompany.id=development_costs.cid and c_time>=".$min_c_time." and c_time<='".$max_c_time."' and is_deleted='0'
                                 group by year(c_time) having $price)";
                }
                $where.=$this->formatfilter("",$column,1,"");
            }
        }
        return $where;
    }
    //过滤符合科技申报库类型的企业
    function techfilter($tech,$sortBy="modified",$direction="desc")
    {	
    	$grouplist=$this->Group->getGroupList();
    	$user=$this->Session->read('User');
    	$colstr = "";
    	if(isset($_COOKIE["selectcol"])){
    		$colstr = $_COOKIE["selectcol"];
    		
        }
    	if(isset($_GET["colstr"])){
            $colstr=urldecode($_GET['colstr']);
            $colstr = rtrim($colstr,",");
        }
    	if(empty($colstr)){
    		$colstr = 'contact,income,person,patent';
    	}
    	
    	
       	setcookie("selectcol",$colstr);
        //$colstr = $_COOKIE["selectcol"];
        $selectcolumns = $this->Constant->CompColumn;
        $this->set(compact('colstr','selectcolumns'));
        
        $pagesize=10;
        $paging['show']=$pagesize;
        $paging['url'] = '/searchs/'.$this->action.'/'.$tech.'/'.$sortBy.'/'.$direction;
        $urlcount=0;
        
        $where="";
        $techstacks=$this->Techstack->findAll("Techstack.id='$tech'");
        $sql="CompTechnology.type_id='$tech' and ";
        $techstr="";
        $techdesc="";
        $tname="";
        if($techstacks){
            $objtechstacks=$techstacks[0];
            $techs=$objtechstacks["Techstack"];
            $where.=$this->gettechfilter($techs);
            $techpersons=$objtechstacks["TechPerson"];
            $where.=$this->gettechpersonfilter($techpersons);
            $techeconomics=$objtechstacks["TechEconomic"];
            $where.=$this->gettecheconomicfilter($techeconomics);
            $techpatents=$objtechstacks["TechPatent"];
            $where.=$this->gettechpatentfilter($techpatents);
            $techdevelopmentcosts=$objtechstacks["TechDevelopmentCost"];
            $where.=$this->gettechdevelopmentcostfilter($techdevelopmentcosts);
            $strdesc=$this->strdesc;
        }
        
        $where.="SearchCompany.is_deleted='0'";
        if(empty($_GET['group'])){
        	if(!$user['isadmin']){
        		if(!$user['isvisitor']){
				 $where.="  and SearchCompany.groupid = '".$user['groupid']."'";  
        		}     		  		
        	}
        }else{
        	 $where.=" and  SearchCompany.groupid = '".$_GET['group']."'";
        }        
        $group_mod_id=$_GET['group'];
        $urlcount=$this->SearchCompany->findCount($where);
        //if($sortBy=="modified"){
        //	$this->Session->setFlash('共检索出'.$urlcount.'条记录');
        //}
        $paging['total'] =$urlcount;
        $showpage=0;
        $companys=array();
        
        $sort="desc";
        $capitalsort=$sort;
        $regsort=$sort;
        $columncapital="";
        if($sortBy=="capital"){
            $columncapital=$this->Codetype->getcapital().',';
            if($direction=="desc"){
                $capitalsort="asc";
            }
        }
        if($sortBy=="reg_time"){
            if($direction=="desc"){
                $regsort="asc";
            }
        }
        $this->set(compact('capitalsort','regsort'));
        
        $showpage=0;
        $companys=array();
        if ($paging['total'] > 0) {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
            $this->SearchCompany->bindModel(
            	array('hasMany'=>array(
            		'SearchPerson'=>array( 
            			'className'=>'SearchPerson',
                        'foreignKey'=>'cid',	
                        'conditions'=>array("SearchPerson.is_deleted='0'"),
                        'order'=>'SearchPerson.contypeid desc',
                        'fields'=>array('SearchPerson.id')
       		))));
       		//$patentname=$this->Codetype->getCValues($this->Constant->PatentType,1);
       		$this->SearchCompany->bindModel(
                array('hasMany' => array(
                'CompEconomic' => array (
	                'conditions' => array("CompEconomic.is_deleted='0' and CompEconomic.state = '1'"),
	                'fields'=>"CompEconomic`.`general_income`",
	                'order'=>'CompEconomic.company_year desc,CompEconomic.month desc',
	                'className' => 'CompEconomic',
	                'foreignKey' => 'cid',
                	'limit'=>'1')
                ))
            );
            
            $this->SearchCompany->bindModel(
                array('hasMany' => array(
                'CompanyPatent' => array (
	                'conditions' => array("CompanyPatent.is_deleted='0' and CompanyPatent.state = '2' or CompanyPatent.state = '3'"),
	                'fields'=>"CompanyPatent`.`id`",
	                //'order'=>'CompTalent.declarate_status desc',
	                'className' => 'CompanyPatent',
	                'foreignKey' => 'cid')
                ))
            );
            $order=$sortBy." ".$direction;
            $companys=$this->SearchCompany->findAll($where,
            "`SearchCompany`.`id`,`SearchCompany`.`company_name`,`SearchCompany`.`reg_time`,`SearchCompany`.`groupid`,
            `SearchCompany`.`capital`,$columncapital `SearchCompany`.`cap_type`,`SearchCompany`.`tel`,`SearchCompany`.`contact`",$order,$limit,$page);
            
            if($urlcount>$pagesize)
            {
                $showpage=1;
            }
        }
        //debug($companys);
        $this->set(compact('group_mod_id','companys','showpage','tech','strdesc','grouplist'));
    }
    //过滤符合人才申报库类型的企业
    function talentfilter($tech,$sortBy="modified",$direction="desc")
    {
        $this->techfilter($tech,$sortBy,$direction);
    }
    //过滤符合科技金融申报库类型的企业
    function finacefilter($tech,$sortBy="modified",$direction="desc")
    {
        $this->techfilter($tech,$sortBy,$direction);
    }
    //人才项目申报库
    function talentdb()
    {
        $this->loadModel("Constant");
        $this->loadModel("Codetype");
        $grouplist=$this->Group->getGroupList();
        $techtype=$this->Codetype->getSubType($this->Constant->TalstackType,"-",1);
        $talstacktype=$this->Codetype->getSubType($this->Constant->TalstackType);	
        $industrys=$this->Codetype->getCValues($this->Constant->Industry,"all");
        $dstatus=$this->Codetype->getCValues($this->Constant->Declarate_Status,1);
        $this->set(compact('industrys','techtype','talstacktype','dstatus'));
        $this->Talstack->unbindModel(array ('belongsTo' => array ('Codevalue')));
        $taltype=$this->Talstack->getTname();
        $subtype1="";
        $subtype2="";
        $this->set(compact('taltype'));
        $selectdeclaretype=null;
        $selecttalstacktype=null;
        $selectdstatus=null;
        $selecttype1=null;
        $selecttype2=null;
        $pagesize=10;
        $paging['show']=$pagesize;
        $paging['url'] = '/searchs/talentdb/';
        $year="";
        if(!empty($_GET['year'])){
            $year=$_GET['year'];
        }
        $tal="";
        $gov="";
        if(!empty($_GET['tal'])){
            $tal=$_GET['tal'];
        }
        if(!empty($_GET['dstatus'])){
            $selectdstatus=$_GET['dstatus'];
        }
        if(!empty($_GET['gov'])){
            $selecttalstacktype=$_GET['gov'];
        }
        $group='';
        if(!empty($_GET['group'])){
        	$group=$_GET['group'];
        }
        $group_mod_id=$_GET['group'];
        $sql="";
        $isflag=false;
        $keyword="";
        if(!empty($_GET['keyword'])){
            $keyword=$_GET['keyword'];
            $sql.="(CompTalent.declare_name like '%".urldecode($keyword)."%') and ";
            $isflag=true;
        }
        
        if(!empty($_GET['year'])){
            $sql.="year(CompTalent.declare_time)='".$year."' and ";
            $isflag=true;
        }
        if(!empty($_GET['gov']) && empty($_GET['tal'])){
            $sql.=$this->Talstack->getidlistgov($selecttalstacktype);
            $isflag=true;
        }
        if(!empty($_GET['dstatus'])){
            $sql.="CompTalent.declarate_status='".$selectdstatus."' and ";
            $isflag=true;
        }
            //增加模块检索
        $cuser=$this->Session->read('User');
        if(!$cuser['isadmin']&&!$cuser['isvisitor']){
			$isflag=true;
        	$sql.="Company.groupid='".$cuser["groupid"]."' and ";		
        }else{
        	if(!empty($_GET['group'])){
        		$isflag=true;
        		$sql.="Company.groupid='".$_GET['group']."' and ";
        	}
        }
        $group_mod_id=$_GET['group'];
        if(!empty($_GET['tal'])){
            $isflag=true;
            $this->Talstack->tid="";
            $this->Talstack->showtname($tal);
            $tid=rtrim($this->Talstack->tid,"/");
            $objtid=explode('/',$tid);
            $selectdeclaretype=$objtid[0];
            $cobjtid=count($objtid);
            
            if($cobjtid>1){
                $selecttype1=$objtid[1];
            }
            if($cobjtid>2){
                $selecttype2=$objtid[2];
            }
            if($selectdeclaretype){
                $this->Talstack->unbindModel(array ('belongsTo' => array ('Codevalue')));
                $subtype1=$this->Talstack->getTname($selectdeclaretype);
            }
            if(!empty($selecttype1)){
                $this->Talstack->unbindModel(array ('belongsTo' => array ('Codevalue')));
                $subtype2=$this->Talstack->getTname($selecttype1);
            }
            if($cobjtid==1){
                $s="'$selectdeclaretype'";
                $this->Talstack->unbindModel(array ('belongsTo' => array ('Codevalue')));
                $objsubtype1=$this->Talstack->getTname($selectdeclaretype);
                foreach ($objsubtype1 as $key1=>$tid){
                    if($key1){
                        $s.=",'".$key1."'";
                        $this->Talstack->unbindModel(array ('belongsTo' => array ('Codevalue')));
                        $objsubtype2=$this->Talstack->getTname($key1);
                        if($objsubtype2){
                            foreach ($objsubtype2 as $key2=>$tids){
                                if($key2){
                                    $s.=",'".$key2."'";
                                }
                            }
                        }
                    }
                }
                $sql.="CompTalent.type_id in(".$s.") and ";
            }
            if($cobjtid==2){
                $s1="'$selecttype1'";
                if($subtype2){
                    foreach ($subtype2 as $key=>$tid){
                        if($key){
                            $s1.=",'".$key."'";
                        }
                    }
                }
                $sql.="CompTalent.type_id in(".$s1.") and ";
            }
            if($cobjtid==3){
                $sql.="CompTalent.type_id='".$selecttype2."' and ";
            }
        }
        $this->set(compact('group_mod_id','subtype1','subtype2','selecttype1','selecttype2'));
        $urlcount=0;
        $where="";
        $enterprise="";
        if(!empty($_GET['enterprise'])){
            $enterprise=$_GET['enterprise'];
            $where.="(SearchCompany.company_name like '%".urldecode($enterprise)."%') and ";
        }
        if($isflag){
            $this->CompTalent->unbindModel(array ('hasMany' => array ('Attachment')));
            $objcids=$this->CompTalent->findAll("$sql CompTalent.is_deleted='0'","CompTalent.cid");
            $cidlist="";
            foreach ($objcids as $cid){
                $cidlist.="'".$cid["CompTalent"]["cid"]."',";
            }
            if($cidlist){
                $where.="SearchCompany.id in (".rtrim($cidlist,",").") and ";
            }else{
                $where.="SearchCompany.id in (1) and ";
            }
        }
        
        //$keyword="";
        $industry="";
        if(!empty($_GET['industry'])){
            $industry=$_GET['industry'];
            $this->loadModel("ProCvalue");
            $objpidlist=$this->ProCvalue->findAllByCvid($industry);
            $pidlist="";
            if($objpidlist){
                foreach ($objpidlist as $pid){
                    $pidlist.="'".$pid["ProCvalue"]["pid"]."',";
                }
            }
            $wheres=rtrim($pidlist,",");	
            if(empty($wheres)){
                $wheres=1;
            }
            $where.="SearchCompany.id in (".$wheres.") and ";
        }
        
        //if(!empty($_GET['keyword'])){
        //	$keyword=$_GET['keyword'];
        //	$where.="(SearchCompany.company_name like '%".urldecode($keyword)."%') and ";
        //}
        
        $where.="SearchCompany.is_deleted='0'";
        $urlcount=$this->SearchCompany->findCount($where);
        if(!empty($_GET['year']) || !empty($_GET['tal'])||!empty($_GET['gov'])||!empty($_GET['dstatus'])){
            $this->Session->setFlash('共检索出'.$urlcount.'条记录');
        }
        $paging['total'] =$urlcount;
        $showpage=0;
        $companys=array();
        $all_company_names = $this->SearchCompany->findAll($where,"SearchCompany.company_name");
        if ($paging['total'] > 0) {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
            $this->SearchCompany->bindModel(
                array('hasMany' => array(
                'CompTalent' => array (
                'conditions' => array("$sql CompTalent.is_deleted='0'"),
                'fields'=>"CompTalent`.`id`, `CompTalent`.`declare_name`, `CompTalent`.`type_id`,`CompTalent`.`declarate_status`,`CompTalent`.`declare_time`",
                'order'=>'CompTalent.declarate_status desc',
                'className' => 'CompTalent',
                'foreignKey' => 'cid',)
                ))
            );
            $companys=$this->SearchCompany->findAll($where,"SearchCompany.id,SearchCompany.company_name,SearchCompany.groupid","SearchCompany.modified desc",$limit,$page);
            if($urlcount>$pagesize)
            {
                $showpage=1;
            }
        }
        $this->set(compact('group_mod_id','all_company_names','companys','showpage','year','selectdeclaretype','selecttalstacktype','selectdstatus','keyword','industry','enterprise','grouplist'));
    }
    //所有企业的金融信息
    function allfinace()
    {
        $pagesize=10;
        $paging['show']=$pagesize;
        $paging['url'] = '/searchs/allfinace/';
        $grouplist=$this->Group->getGroupList();
        $industrys=$this->Codetype->getCValues($this->Constant->Industry,"all");
        $this->set(compact('industrys'));
        $urlcount=0;
        $keyword="";
        $industry = "";
        $companys = array();
        $enterprise="";
        $where="";
        $year="";
        if(!empty($_GET['year'])){
            $year=$_GET['year'];;
        }
        $group='';
        if(!empty($_GET['group'])){
        	$group=$_GET['group'];
        }
        $group_mod_id=$_GET['group'];
        $isflag=false;
        $sql="";
        if(!empty($_GET['year'])){
            $isflag=true;
            $sql="year(CompFinacerelease.modified)='$year' and";
        }
            //增加模块检索
        $cuser=$this->Session->read('User');
        if(!$cuser['isadmin']&&!$cuser['isvisitor']){
			$isflag=true;
        	$sql.="Company.groupid='".$cuser["groupid"]."' and ";		
        }else{
        	if(!empty($_GET['group'])){
        		$isflag=true;
        		$sql.="Company.groupid='".$_GET['group']."' and ";
        	}
        }   
        $group_mod_id=$_GET['group'];
        $keyword="";
        if(!empty($_GET['keyword'])){
            $isflag=true;
            $keyword=$_GET['keyword'];
            $sql.=" CompFinacerelease.title like '%".urldecode($keyword)."%' and ";
        }
        if($isflag){
            $this->CompTechnology->unbindModel(array ('hasMany' => array ('Attachment'),'belongsTo' => array ('type_id')));
            $objcids=$this->CompFinacerelease->findAll("$sql CompFinacerelease.is_deleted='0'","CompFinacerelease.cid");
            $cidlist="";
            foreach ($objcids as $cid){
                $cidlist.="'".$cid["CompFinacerelease"]["cid"]."',";
            }
            if($cidlist){
                $where.="Company.id in (".rtrim($cidlist,",").") and ";
            }else{
                $where.="Company.id in (1) and ";
            }
        }
        $industry="";
        if(!empty($_GET['industry'])){
            $industry=$_GET['industry'];
            $this->loadModel("ProCvalue");
            $objpidlist=$this->ProCvalue->findAllByCvid($industry);
            $pidlist="";
            if($objpidlist){
                foreach ($objpidlist as $pid){
                    $pidlist.="'".$pid["ProCvalue"]["pid"]."',";
                }
            }
            $wheres=rtrim($pidlist,",");	
            if(empty($wheres)){
                $wheres=1;
            }
            $where.="Company.id in (".$wheres.") and ";
        }
        if(!empty($_GET['enterprise'])){
            $enterprise=$_GET['enterprise'];
            $where.="(Company.company_name like '%".urldecode($enterprise)."%') and ";
        }
        $where.="Company.is_deleted='0'";
        $urlcount=$this->Company->findCount($where);
        if(!empty($_GET['year']) || !empty($_GET['keyword'])){
            $this->Session->setFlash('共检索出'.$urlcount.'条记录');
        }
        $paging['total'] =$urlcount;
        $showpage=0;
        $companys=array();
        if ($paging['total'] > 0) {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
            $this->Company->bindModel(
                array('hasMany' => array(
                'CompFinacerelease' => array (
                'conditions' => array(" $sql is_deleted='0'"),
                'fields'=>"`CompFinacerelease`.`id`,`CompFinacerelease`.`title`, `CompFinacerelease`.`modified`, `CompFinacerelease`.`amount`,
             `CompFinacerelease`.`requirement`",
                'order'=>'CompFinacerelease.modified asc',
                'className' => 'CompFinacerelease',
                'foreignKey' => 'cid',)
                ))
            );
            $companys=$this->Company->findAll($where,"Company.id,Company.company_name,Company.groupid","Company.modified desc",$limit,$page);
            if($urlcount>$pagesize)
            {
                $showpage=1;
            }
        }
        
        
        $this->set(compact('group_mod_id','companys','showpage','keyword','industry','year','enterprise','grouplist'));
    }
    function showfinacedetail($id)
    {
        $this->CompFinacerelease->id = $id;
        $finacereleases= $this->CompFinacerelease->read();
        $this->set(compact('finacereleases'));
    }
    
    function filter()
    {
        $pagesize=10;
        $paging['show']=$pagesize;
        $paging['url'] = '/searchs/filter/';
        $urlcount=0;
        $where="";
        $urlcount=$this->Techstack->findCount($where);
        $paging['total'] =$urlcount;
        $showpage=0;
        $projects=array();
        if ($paging['total'] > 0) {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
            $techstacks=$this->Techstack->findAll($where,null,
            "Techstack.modified desc",$limit,$page);
            if($urlcount>$pagesize)
            {
                $showpage=1;
            }
        }
        $this->set(compact('techstacks','showpage'));
    }
    function getpagefilter($filtertype,$flag="delaction"){
        $action1="index";
        $action2="techfilter";
        $actions="";
        switch ($filtertype){
            case "2":
                $action1="talentdb";
                $action2="talentfilter";
                break;
            case "3":
                $action1="allfinace";
                $action2="finacefilter";
                break;
            default:
                break;
        }
        $actions=$action1;
        if($flag=="editaction"){
            $actions=$action2;
        }
        return $actions;
    }
    function delfilter($id,$filtertype){
        $this->Techstack->del($id,true);
        $this->Session->setFlash('科技项目申报删除成功');
        $actions=$this->getpagefilter($filtertype);
        $this->redirect(array('action'=>$actions));
    }
    function checktechname($techname)
    {
        $isflag=0;
        $objname=array();
        $objname=$this->Techstack->findCount("Techstack.name='".urldecode($techname)."'");
        if($objname>0){
            $isflag=1;
        }
        print($isflag);
        exit();
    }
    function settechfilter($id=null){
        $educations=$this->Constant->Education;
        unset($educations[2]);
        unset($educations[3]);
        $education[""]="请选择学历";
        foreach ($educations as $key=>$ed){
            $education[$key]=$ed.'以上';
        }
        $patenttype = $this->Codetype->getCValues($this->Constant->PatentType,1);
        $patenttype=array_merge(array(""=>"请选择专利"),$patenttype);
        $charge=$this->Codetype->getCValues($this->Constant->Depart_Charge);
        $this->set(compact('id','charge','education','patenttype')); 
        if($id){
            $this->set('tech',$id);
            $objTech=$this->Techstack->findById($id);
            $this->data=$objTech;
            $reg_mintime=$objTech['Techstack']['reg_mintime'];
            $reg_maxtime=$objTech['Techstack']['reg_maxtime'];
            App::import('Helper','Str');
            $str=new StrHelper();
            if(!empty($reg_mintime)){
               $reg_mintime=$str->formattime($reg_mintime);
               $this->data['Techstack']['reg_mintime']=$reg_mintime;
            }
            if(!empty($reg_maxtime)){
               $reg_maxtime=$str->formattime($reg_maxtime);
               $this->data['Techstack']['reg_maxtime']=$reg_maxtime;
            }
        }else{
            if(!empty($this->data)){
                $reg_mintime=$this->data["Techstack"]["reg_mintime"];
                if(empty($reg_mintime)){
                    $this->data["Techstack"]["reg_mintime"]=null;
                }
                $reg_maxtime=$this->data["Techstack"]["reg_maxtime"];
                if(empty($reg_maxtime)){
                    $this->data["Techstack"]["reg_maxtime"]=null;
                }
                $this->Techstack->saveAll($this->data);
                $this->Session->setFlash('保存成功');
                $techid=$this->data['Techstack']['id'];
                if($techid){
                    $filtertype=$this->data["Techstack"]['type'];
                    $actions=$this->getpagefilter($filtertype,"editaction");
                    $this->redirect(array('action'=>$actions,$techid));
                }else{
                    $this->redirect($this->referer());
                }
            }
        }
    }	
    function settalentfilter($id=null){
        $this->settechfilter($id);
    }
    function setfinacefilter($id=null){
        $this->settechfilter($id);
    }
    function showfilter($id){
        $this->editfilter($id);
    }
    
    //企业载体租赁汇总
    function carrierlease($report = null){
        $forbids=$this->Codetype->getCValues($this->Constant->Forbid);//入驻划区
        $pagesize=10;
        $paging['show']=$pagesize;
        $paging['url'] = '/searchs/carrierlease/';
        $urlcount=0;
        
        $where = "";
        $sql = "";
        $deadlinedays="";
        if(!empty($_GET['deadlinedays'])){
            $deadlinedays=$_GET['deadlinedays'];
            $sql ="CompCarrierlease.deadline <=(select date_add(now(), interval ".$deadlinedays." day)) and CompCarrierlease.deadline >=now() and ";
        }
        $objcids=$this->CompCarrierlease->findAll("$sql CompCarrierlease.is_deleted='0'","CompCarrierlease.cid");
        $cidlist="";
        foreach ($objcids as $cid){
            $cidlist.="'".$cid["CompCarrierlease"]["cid"]."',";
        }
        if($cidlist){
            $where.="SearchCompany.id in (".rtrim($cidlist,",").") and ";
        }else{
            $where.="SearchCompany.id in (1) and ";
        }
        
        $where .="SearchCompany.is_deleted='0'";
        $urlcount=$this->SearchCompany->findCount($where);
        if(!empty($_GET['deadlinedays'])){
            $this->Session->setFlash('共检索出'.$urlcount.'条记录');
        }
        $paging['total'] =$urlcount;
        $showpage=0;
        
        $companys=array();
        if ($paging['total'] > 0) {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
            $this->SearchCompany->bindModel(
                array('hasMany' => array(
                'CompCarrierlease' => array (
                'conditions' => array(" $sql is_deleted='0'"),
                'fields'=>"`CompCarrierlease`.`id`,`CompCarrierlease`.`location`,
                `CompCarrierlease`.`area`,`CompCarrierlease`.`starttime`,`CompCarrierlease`.`deadline`, `CompCarrierlease`.`rent`, `CompCarrierlease`.`forbid`",
                'className' => 'CompCarrierlease',
                'foreignKey' => 'cid')
                ))
            );
            if(empty($report)){
                $companys=$this->SearchCompany->findAll($where,"SearchCompany.id,SearchCompany.pid,SearchCompany.company_name","SearchCompany.modified desc",$limit,$page);
            }else{
                $companys=$this->SearchCompany->findAll($where,"SearchCompany.id,SearchCompany.pid,SearchCompany.company_name","SearchCompany.modified desc");
            }
            if($urlcount>$pagesize)
            {
                $showpage=1;
            }
        }
        $this->set(compact('companys','showpage',"deadlinedays","forbids"));
        if($report){
            $this->layout="excel";
            $filename="企业载体租赁信息汇总.xls";
            $this->set(compact('filename','report'));
        }
    }
    //企业宿舍租赁汇总
    function dormlease($report = null){
        $pagesize=10;
        $paging['show']=$pagesize;
        $paging['url'] = '/searchs/dormlease/';
        $urlcount=0;
        
        $where = "";
        $sql = "";
        $deadlinedays="";
        if(!empty($_GET['deadlinedays'])){
            $deadlinedays=$_GET['deadlinedays'];
            $sql ="CompDormitorylease.deadline <=(select date_add(now(), interval ".$deadlinedays." day)) and CompDormitorylease.deadline >=now() and ";
        }
        $objcids=$this->CompDormitorylease->findAll("$sql CompDormitorylease.is_deleted='0'","CompDormitorylease.cid");
        $cidlist="";
        foreach ($objcids as $cid){
            $cidlist.="'".$cid["CompDormitorylease"]["cid"]."',";
        }
        if($cidlist){
            $where.="SearchCompany.id in (".rtrim($cidlist,",").") and ";
        }else{
            $where.="SearchCompany.id in (1) and ";
        }
        
        $where .="SearchCompany.is_deleted='0'";
        $urlcount=$this->SearchCompany->findCount($where);
        if(!empty($_GET['deadlinedays'])){
            $this->Session->setFlash('共检索出'.$urlcount.'条记录');
        }
        $paging['total'] =$urlcount;
        $showpage=0;
        
        $companys=array();
        if ($paging['total'] > 0) {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
            $this->SearchCompany->bindModel(
                array('hasMany' => array(
                'CompDormitorylease' => array (
                'conditions' => array(" $sql is_deleted='0'"),
                'fields'=>"`CompDormitorylease`.`id`,`CompDormitorylease`.`location`,
                `CompDormitorylease`.`area`,`CompDormitorylease`.`starttime`,`CompDormitorylease`.`deadline`, `CompDormitorylease`.`rent`",
                'className' => 'CompDormitorylease',
                'foreignKey' => 'cid',)
                ))
            );
            if(empty($report)){
                $companys=$this->SearchCompany->findAll($where,"SearchCompany.id,SearchCompany.pid,SearchCompany.company_name","SearchCompany.modified desc",$limit,$page);
            }else{
                $companys=$this->SearchCompany->findAll($where,"SearchCompany.id,SearchCompany.pid,SearchCompany.company_name","SearchCompany.modified desc");
            }
            if($urlcount>$pagesize)
            {
                $showpage=1;
            }
        }
        $this->set(compact('companys','showpage',"deadlinedays"));
        if($report){
            $this->layout="excel";
            $filename="企业需求信息汇总（宿舍租赁）.xls";
            $this->set(compact('filename','report'));
        }
    }
	function changevalue($id,$db,$v,$column){
    	$this->layout=null;
    	$this->$db->id=$id;
    	if($v=="-"){
    		$v="";
    	}
    	$this->$db->saveField($column,$v);
    	exit();
    }
    //企业人才需求汇总
    function talentdemand($report = null){
    	
    	$user=$this->Session->read('User');
    	$grouplist=$this->Group->getGroupList();
        $pagesize=10;
        $paging['show']=$pagesize;
        $paging['url'] = '/searchs/talentdemand/';
        $urlcount=0;
        
        $where = "";
        $sql = "";
        $occupation="";
        if(!empty($_GET['occupation'])){
            $occupation=$_GET['occupation'];
            $sql ="CompJobapply.category like '%".$occupation."%' and ";
        }
        $objcids=$this->CompJobapply->findAll("$sql CompJobapply.is_deleted='0'","CompJobapply.cid");
        $cidlist="";
        foreach ($objcids as $cid){
            $cidlist.="'".$cid["CompJobapply"]["cid"]."',";
        }
        if($cidlist){
            $where.="SearchCompany.id in (".rtrim($cidlist,",").") and ";
        }else{
            $where.="SearchCompany.id in (1) and ";
        }
        if(empty($_GET['group'])){   	
        	if(!$user['isadmin']){
        		if(!$user['isvisitor']){
				 $where.=" SearchCompany.groupid = '".$user['groupid']."' and ";   
        		}    		  		
        	}
        }else{
        	 $where.=" SearchCompany.groupid = '".$_GET['group']."' and ";
        }
        $group_mod_id=$_GET['group'];
        
        $where .= "SearchCompany.is_deleted='0'";
        $urlcount=$this->SearchCompany->findCount($where);
        if(!empty($_GET['occupation'])){
            $this->Session->setFlash('共检索出'.$urlcount.'条记录');
        }
        
        $paging['total'] =$urlcount;
        $showpage=0;
        
        $companys=array();
        if ($paging['total'] > 0) {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
            $this->SearchCompany->bindModel(
                array('hasMany' => array(
                'CompJobapply' => array (
                'conditions' => array(" $sql is_deleted='0'"),
                'fields'=>"`CompJobapply`.`id`,`CompJobapply`.`category`,
                `CompJobapply`.`releasedate`,`CompJobapply`.`numberofapply`,`CompJobapply`.`jobdesc`",
                'className' => 'CompJobapply',
                'foreignKey' => 'cid',)
                ))
            );
            if(empty($report)){
                $companys=$this->SearchCompany->findAll($where,"SearchCompany.id,SearchCompany.pid,SearchCompany.company_name","SearchCompany.modified desc",$limit,$page);
            }else{
                $companys=$this->SearchCompany->findAll($where,"SearchCompany.id,SearchCompany.pid,SearchCompany.company_name","SearchCompany.modified desc");
            }
            if($urlcount>$pagesize)
            {
                $showpage=1;
            }
        }
        $this->set(compact('group_mod_id','companys','showpage',"occupation","grouplist"));
        if($report){
            $this->layout="excel";
            $filename="企业需求信息汇总（人才需求）.xls";
            $this->set(compact('filename','report'));
        }
    }
    
    //融资需求汇总
    function financedemand($report = null){
    	
    	$user=$this->Session->read('User');
    	$grouplist=$this->Group->getGroupList();
        $pagesize=10;
        $paging['show']=$pagesize;
        $paging['url'] = '/searchs/financedemand/';
        $urlcount=0;
        
        $where = "";
        $sql = "";
        $requirement="";
        if(!empty($_GET['requirement'])){
            $requirement=$_GET['requirement'];
            $sql ="CompFinacerelease.requirement like '%".$requirement."%' and ";
        }
        $objcids=$this->CompFinacerelease->findAll("$sql CompFinacerelease.is_deleted='0'","CompFinacerelease.cid");
        $cidlist="";
        foreach ($objcids as $cid){
            $cidlist.="'".$cid["CompFinacerelease"]["cid"]."',";
        }
        if($cidlist){
            $where.="SearchCompany.id in (".rtrim($cidlist,",").") and ";
        }else{
            $where.="SearchCompany.id in (1) and ";
        }
        if(empty($_GET['group'])){   	
        	if(!$user['isadmin']){
        		if(!$user['isvisitor']){
				 $where.=" SearchCompany.groupid = '".$user['groupid']."' and "; 
        		}      		  		
        	}
        }else{
        	 $where.=" SearchCompany.groupid = '".$_GET['group']."' and ";
        }       
        $group_mod_id=$_GET['group'];
        
        $where .="SearchCompany.is_deleted='0'";
        $urlcount=$this->SearchCompany->findCount($where);
        if(!empty($_GET['requirement'])){
            $this->Session->setFlash('共检索出'.$urlcount.'条记录');
        }
        
        $paging['total'] =$urlcount;
        $showpage=0;
        
        $companys=array();
        if ($paging['total'] > 0) {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
            $this->SearchCompany->bindModel(
                array('hasMany' => array(
                'CompFinacerelease' => array (
                'conditions' => array(" $sql is_deleted='0'"),
                'fields'=>"`CompFinacerelease`.`id`,`CompFinacerelease`.`requirement`,
                `CompFinacerelease`.`amount`,`CompFinacerelease`.`title`,`CompFinacerelease`.`created`",
                'className' => 'CompFinacerelease',
                'foreignKey' => 'cid',)
                ))
            );
            if(empty($report)){
                $companys=$this->SearchCompany->findAll($where,"SearchCompany.id,SearchCompany.pid,SearchCompany.company_name,SearchCompany.groupid","SearchCompany.modified desc",$limit,$page);
            }else{
                $companys=$this->SearchCompany->findAll($where,"SearchCompany.id,SearchCompany.pid,SearchCompany.company_name,SearchCompany.groupid","SearchCompany.modified desc");
            }
            if($urlcount>$pagesize)
            {
                $showpage=1;
            }
        }
        $this->set(compact('group_mod_id','companys','showpage',"requirement","grouplist"));
        if($report){
            $this->layout="excel";
            $filename="企业需求信息汇总（融资需求）.xls";
            $this->set(compact('filename','report'));
        }
    }
    //其它需求汇总
    function publishdemand($report = null){
        
    	$user=$this->Session->read('User');
    	$grouplist=$this->Group->getGroupList();
    	$type=$this->Codetype->getCValues($this->Constant->Require_Type);
        $pagesize=10;
        $paging['show']=$pagesize;
        $paging['url'] = '/searchs/publishdemand/';
        $urlcount=0;
        
        $where = "";
        $sql = "";
        $publishtitle="";
        if(!empty($_GET['publishtitle'])){
            $publishtitle=$_GET['publishtitle'];
            $sql ="CompDemand.title like '%".$publishtitle."%' and ";
        }
        $objcids=$this->CompDemand->findAll("$sql CompDemand.is_deleted='0'","CompDemand.cid");
        $cidlist="";
        foreach ($objcids as $cid){
            $cidlist.="'".$cid["CompDemand"]["cid"]."',";
        }
        if($cidlist){
            $where.="SearchCompany.id in (".rtrim($cidlist,",").") and ";
        }else{
            $where.="SearchCompany.id in (1) and ";
        }
        
        if(empty($_GET['group'])){   	
        	if(!$user['isadmin']){
        		if(!$user['isvisitor']){
				 $where.=" SearchCompany.groupid = '".$user['groupid']."' and ";  
        		}     		  		
        	}
        }else{
        	 $where.=" SearchCompany.groupid = '".$_GET['group']."' and ";
        }
         $group_mod_id=$_GET['group'];       
        $where .="SearchCompany.is_deleted='0'";
        $urlcount=$this->SearchCompany->findCount($where);
        if(!empty($_GET['publishtitle'])){
            $this->Session->setFlash('共检索出'.$urlcount.'条记录');
        }
        $paging['total'] =$urlcount;
        $showpage=0;
        
        $companys=array();
        if ($paging['total'] > 0) {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
            $this->SearchCompany->bindModel(
                array('hasMany' => array(
                'CompDemand' => array (
                'conditions' => array(" $sql is_deleted='0'"),
                'fields'=>"`CompDemand`.`id`,`CompDemand`.`publisher`,
                `CompDemand`.`validity`,`CompDemand`.`title`,`CompDemand`.`need`,`CompDemand`.`require_type`,`CompDemand`.`created`",
                'className' => 'CompDemand',
                'foreignKey' => 'cid',)
                ))
            );
            if(empty($report)){
                $companys=$this->SearchCompany->findAll($where,"SearchCompany.id,SearchCompany.pid,SearchCompany.company_name,SearchCompany.groupid","SearchCompany.modified desc",$limit,$page);
            }else{
                $companys=$this->SearchCompany->findAll($where,"SearchCompany.id,SearchCompany.pid,SearchCompany.company_name,SearchCompany.groupid","SearchCompany.modified desc");
            }
            if($urlcount>$pagesize)
            {
                $showpage=1;
            }
        }
        $this->set(compact('group_mod_id','companys','showpage',"publishtitle","type","grouplist"));
        if($report){
            $this->layout="excel";
            $filename="企业需求信息汇总（其它需求）.xls";
            $this->set(compact('filename','report'));
        }
    }
    
    
    //根据联系人姓名查询企业的ID
    function getCompanyIdByPerson($person)
    {
        $this->loadModel("SearchPerson");
        $cidlist = "";
        $sql = "";
        $sql .= "SearchPerson.is_deleted = '0'";
        if(!empty($person))
        {
            $sql .= " and SearchPerson.person_name like '%".urldecode($person)."%'";
        }
        $objperson = $this->SearchPerson->findAll($sql,'SearchPerson.cid');
        //debug($objperson);
        foreach($objperson as $man)
        {
            $cidlist .= "'".$man["SearchPerson"]["cid"]."',";
        }
        return $cidlist;
    }

    function companyperson()
    {
    	$grouplist=$this->Group->getGroupList();
    	$user=$this->Session->read('User');
        //获取所有用户
        $objusers=$this->Session->read('AllUserList');
        $flag = true;
        $where = "";
        $company_ids = array();
        $contype=$this->Codetype->getCValues($this->Constant->Contype);	//获取负责方向
        unset($contype[""]);
        $industrys=$this->Codetype->getCValues($this->Constant->Industry,"all");//获取产业列表
        $this->set(compact('industrys','contype','objusers'));
        //查询产业
        $industry="";
        if(!empty($_GET['indus'])){
            $industry=rtrim($_GET['indus'],",");//把url中传过来的字符串的最后一个逗号格式化掉
                
            //把传过来的字符串变成数组后遍历，为每个数组元素加上一个单引号，并把数组的每个元素以逗号隔开形式存放到一个industrylist变量中
            $industry_id_list = explode(",", $industry);
            $industrylist = '';
            foreach($industry_id_list as $indi)
            {
                $industrylist .= "'".$indi."',";
            }
            $industrylist = rtrim($industrylist,",");
                
            $this->loadModel("ProCvalue");
            $sql = "ProCvalue.cvid in (".$industrylist.")";
            $objpidlist = $this->ProCvalue->findAll($sql,'ProCvalue.pid');
            $pidlist="";
            if($objpidlist){
                foreach ($objpidlist as $pid){
                    $pidlist.="'".$pid["ProCvalue"]["pid"]."',";
                }
            }
            $wheres=rtrim($pidlist,",");
            if(empty($wheres)){
                $wheres=1;
            }
            $where.="SearchCompany.id in (".$wheres.") and ";
        }

        if(empty($_GET['group'])){
        	if(!$user['isadmin']){
        		if(!$user['isvisitor']){
				 $where.=" SearchCompany.groupid = '".$user['groupid']."' and ";  
        		}     		  		
        	}
        }else{
        	 $where.=" SearchCompany.groupid = '".$_GET['group']."'  and ";
        }        
        $group_mod_id=$_GET['group'];
                
        $sql = "SearchPerson.is_deleted='0'";
        //查询选定负责方向的人员
        $direction = "";
        if(!empty($_GET['contype']))
        {
            $direction = rtrim(urldecode($_GET['contype']),",");
            $direction_id_list = explode(",", $direction);

            $directionlist = '';
            foreach($direction_id_list as $dir)
            {
                $directionlist.="'".$dir."',";
            }
            $directionlist = rtrim($directionlist,",");
            $sql.=" and SearchPerson.contypeid in (".$directionlist.")";
        }

        $faren = "";
        if(isset($_GET["faren"]) && empty($_GET['contype']))
        {
            $faren = urldecode($_GET["faren"]);
            $sql.=" and SearchPerson.contypeid = '0'";
        }

        //查询企业
        $keyword="";
        if(!empty($_GET['keyword'])){
            $keyword=$_GET['keyword'];
            $where.="SearchCompany.company_name like '%".urldecode($keyword)."%' and ";
        }

        $where .= "SearchCompany.is_deleted = '0'";
        //查询人员
        $person="";
        if(!empty($_GET['person'])){
            $person=$_GET['person'];
                
            $cids = '';
            $cids = $this->getCompanyIdByPerson($person);//获取联系人所在企业的id
            $cids = rtrim($cids,",");
            $company = $this->SearchCompany->findAll("SearchCompany.contact like '%".urldecode($person)."%' and SearchCompany.is_deleted='0'",'SearchCompany.id');
                
            if(!empty($cids) && !empty($company)) //如果联系人和法人都包含这个关键字
            {
                foreach($company as $comp)
                {
                    $company_ids[] = $comp["SearchCompany"]["id"];
                }
                $where.=" and (SearchCompany.contact like '%".urldecode($person)."%' or SearchCompany.id in ($cids))";

            }
            else
            {
                if(!empty($cids) && empty($company)) //如果联系人包含这个关键字而法人不包含这个关键字
                {
                    $where .= " and SearchCompany.id in ($cids)";
                    $flag = false;
                }
                else
                $where .= " and SearchCompany.contact like '%".urldecode($person)."%'";

            }
                
        }

        if($person != "")
        $sql .= " and SearchPerson.person_name like '%".urldecode($person)."%'";


       
        //$objcompanies = $this->SearchCompany->findAll($where,'SearchCompany.company_name,SearchCompany.contact,SearchCompany.tel,SearchCompany.email,SearchCompany.id,CompPage.info');
		 //分页
        $pagesize=5;
        $paging['show']=$pagesize;
        $paging['url'] = '/searchs/companyperson/';
        $urlcount=0;
       list ($order, $limit, $page) = $this->Pagination->init("", $paging);
             $this->SearchCompany->bindModel(array(
	        	'hasMany'=>array(
	        		'SearchPerson'=>array( 'className'=>'SearchPerson',
	           		'foreignKey'=>'cid',	
	            	'conditions'=>array($sql),
	            	'order'=>'SearchPerson.contypeid desc',
	            	'fields'=>array('SearchPerson.person_name','SearchPerson.tel','SearchPerson.email','SearchPerson.contypeid')
	      			)
	        	),
	        	'hasOne'=>array(
	        		'CompPage'=>array(
	        			'className'=>'CompPage',
	        			'foreignKey'=>'cid',
	        			'conditions' => '',  
	            		'order' => '',
	        			'fields'=>array('CompPage.info'), 
	        		)
	        	)	        	
	        ));
        $urlcount=$this->SearchCompany->findCount($where);
        $paging["total"]= $urlcount;
        if ($paging['total'] > 0) {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
             $this->SearchCompany->bindModel(array(
	        	'hasMany'=>array(
	        		'SearchPerson'=>array( 'className'=>'SearchPerson',
	           		'foreignKey'=>'cid',	
	            	'conditions'=>array($sql),
	            	'order'=>'SearchPerson.contypeid desc',
	            	'fields'=>array('SearchPerson.person_name','SearchPerson.tel','SearchPerson.email','SearchPerson.contypeid')
	      			)
	        	),
	        	'hasOne'=>array(
	        		'CompPage'=>array(
	        			'className'=>'CompPage',
	        			'foreignKey'=>'cid',
	        			'conditions' => '',  
	            		'order' => '',
	        			'fields'=>array('CompPage.info'), 
	        		)
	        	)	        	
	        ));
   			$objcompanies = $this->SearchCompany->findAll($where,'SearchCompany.company_name,SearchCompany.groupid,SearchCompany.contact,SearchCompany.tel,SearchCompany.email,SearchCompany.id,CompPage.info',
   							"",$limit,$page);
            if($urlcount>$pagesize)
            {
                $showpage=1;
            }
        }
	        
        
        
        $this->set(compact('group_mod_id','objcompanies','industry','keyword','person','flag','company_ids','cids','company','faren','direction','grouplist','showpage'));
    }
    
    //常熟国家大学科技园已投用载体项目入驻情况表
    function carrierin($report = null){
        $forb=$this->Codetype->getCValues($this->Constant->Forbid,1);
        $forbid="";
        $fid="";
        if(!empty($_GET["forbid"])){
            $fid=$_GET["forbid"];
            $forbid="forbid='".$fid."' and";
        }
        $forbids = $this->CompCarrierlease->query("select forbid, count(cid) from comp_carrierleases where $forbid is_deleted = '0' and forbid !='' group by forbid order by forbid desc");
        foreach($forbids as $key=>$forbid){
            $where = "";
            $sql = "CompCarrierlease.forbid='".$forbid["comp_carrierleases"]["forbid"]."' and ";
            $objcids = $this->CompCarrierlease->findAll("$sql CompCarrierlease.is_deleted='0'","CompCarrierlease.cid");
            $cidlist="";
            foreach ($objcids as $cid){
                $cidlist.="'".$cid["CompCarrierlease"]["cid"]."',";
            }
            if($cidlist){
                $where.="SearchCompany.id in (".rtrim($cidlist,",").") and ";
            }else{
                $where.="SearchCompany.id in (1) and ";
            }
            $where .="SearchCompany.is_deleted='0'";
            $companys=array();
            $this->SearchCompany->bindModel(
                array('hasMany' => array(
                'CompCarrierlease' => array (
                'conditions' => array(" $sql is_deleted='0'"),
                'fields'=>"`CompCarrierlease`.`id`,`CompCarrierlease`.`location`,
                `CompCarrierlease`.`area`,`CompCarrierlease`.`starttime`,`CompCarrierlease`.`deadline`, `CompCarrierlease`.`rent`, `CompCarrierlease`.`forbid`",
                'className' => 'CompCarrierlease',
                'foreignKey' => 'cid',)
                ))
            );
            $companys=$this->SearchCompany->findAll($where,"SearchCompany.id,SearchCompany.pid,SearchCompany.company_name,
                                                            SearchCompany.reg_time,SearchCompany.capital,SearchCompany.contact,SearchCompany.workers","SearchCompany.modified desc");
            $forbids[$key]["companys"] = $companys;
        }
//		debug($forbids);
        $forbname="";
        if($fid!=""){
            $forbname="(".$forb[$fid].")";
            $fid="?forbid=".$fid;
        }
        $this->set(compact('forbids','forb','forbname','fid'));
        if($report){
            $this->layout="excel";
            $filename="常熟领军人才已投用载体项目入驻情况表".$forbname.".xls";
            $this->set(compact('filename','report'));
        }
    }
    
    
    
    //打开页面前执行的方法
    function beforeFilter()
    {
        parent::beforeFilter();
        $language = 'chn';
        $this->Session->write('Config.language', $language);
        $user=$this->Session->read('User');
        if (!$user){
            $this->redirect('/users/login');
        }
    }
    //打开页面后执行的方法
    function afterFilter()
    {
        
    }
}
?>